package cn.edu.sdjzu.controller;


import cn.edu.sdjzu.entity.Department;
import cn.edu.sdjzu.factory.ServiceFactory;
import cn.edu.sdjzu.service.DepartmentService;
import cn.edu.sdjzu.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/departCreate.ctl")
public class DepartmentCreateCtrl extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentCreateCtrl.class);
    /**
     * POST, http://localhost:8080/department.ctl, 增加系
     * 增加一个系对象：将来自前端请求的JSON对象，增加到数据库表中
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表参数的JSON字串
        String department_json = JSONUtil.getJSON(request);

        //将JSON字串解析为Department对象
        Department departmentToAdd = JSON.parseObject(department_json, Department.class);
        //前台没有为id赋值，此处模拟自动生成id。如果Dao能真正完成数据库操作，删除下一行。
        departmentToAdd.setId(4 + (int) (Math.random() * 100));

        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加Department对象
        try {
            ServiceFactory.getService(DepartmentService.class, "DepartmentServiceImpl").add(departmentToAdd);
            message.put("message", "增加成功");
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
        } catch (Exception e) {
            message.put("message", "网络异常");
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //读取参数id
        String id_str = request.getParameter("id");
        int id = Integer.parseInt(id_str);

        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();

        //到数据库表中删除对应的系
        try {
            ServiceFactory.getService(DepartmentService.class, "DepartmentServiceImpl").delete(id);
            message.put("message", "删除成功");
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
        } catch (Exception e) {
            message.put("message", "网络异常");
        }
        //响应message到前端
        response.getWriter().println(message);
    }

}

    /**
     * 条件查询、分页响应
     *
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
//    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//
//        //授权验证
////        String idInToken = JwtUtil.parseToken(request);
////        log.debug("id in token=" + idInToken);
//
//        //创建JSON对象message_jsonObj，以便往前端响应信息
//        JSONObject message_jsonObj = new JSONObject();
//        //设置响应字符编码为UTF-8
//        response.setContentType("application/json;charset=UTF-8");
//        //将request body转换为JSON字串
//        String req_jsonStr = JSONUtil.getJSON(request);
//        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
//        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
//        //如果请求body为空
//        if (req_jsonObj == null) {
//            message_jsonObj.put("message", "未收到请求信息！");
//            response.getWriter().println(message_jsonObj);
//            return;
//        }
//        try {
//            //读取分页信息，形成分页对象{"pagination":{"pageNo":1,"pageSize":2}}
//            //将JSON字串解析为Pagination对象
//            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
//            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
//            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
//            //分页获得所有学院
//            Collection<School> schools =
//                    ServiceFactory.getService
//                            (DepartmentService.class, "DepartmentServiceImpl").delete(pagination, conditionList);
//                    SchoolService.getInstance().findAll(pagination, conditionList);
//
////            String schools_json = JSON.toJSONString(
////                    schools, SerializerFeature.DisableCircularReferenceDetect);
//            message_jsonObj.put("totalNum", pagination.getTotalNum());
//            message_jsonObj.put("records", schools);
//            //响应message_jsonObj到前端
//            response.getWriter().println(message_jsonObj);
//        } catch (BaseException e) {
//            message_jsonObj.put("message", e.getMessage());
//            response.getWriter().println(message_jsonObj);
//            e.printStackTrace();
//        } catch (SQLException e) {
//            message_jsonObj.put("message", "数据库操作异常");
//            response.getWriter().println(message_jsonObj);
//            e.printStackTrace();
//        } catch (Exception e) {
//            message_jsonObj.put("message", "网络异常");
//            response.getWriter().println(message_jsonObj);
//        }
//    }

//    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//
//        //授权验证
////        String idInToken = JwtUtil.parseToken(request);
////        log.debug("id in token=" + idInToken);
//
//        //创建JSON对象message_jsonObj，以便往前端响应信息
//        JSONObject message_jsonObj = new JSONObject();
//
//        //设置响应字符编码为UTF-8
//        response.setContentType("application/json;charset=UTF-8");
//        //将request body转换为JSON字串
//        String req_jsonStr = JSONUtil.getJSON(request);
//        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
//        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
//        //如果请求body为空
//        if (req_jsonObj == null) {
//            message_jsonObj.put("message","未收到请求信息！");
//            response.getWriter().println(message_jsonObj);
//            return;
//        }
//
//        try {
//            //读取分页信息，形成分页对象
//            //示例{"pageNo":1,"pageSize":2}
//            //将JSON字串解析为Pagination对象
//            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
//            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
//            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
//            //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
//            this.responseSchools(response, pagination, conditionList);
//
//        }catch (SQLException e){
//            message_jsonObj.put("message", "数据库操作异常");
//            response.getWriter().println(message_jsonObj);
//            e.printStackTrace();
//        }catch(Exception e){
//            message_jsonObj.put("message", "网络异常");
//            response.getWriter().println(message_jsonObj);
//        }
//    }
//}

